<template>
  <div class="table-box" v-loading="loading">
    <ProTable
      ref="proTable"
      title="用户列表"
      rowKey="optid"
      :columns="columns"
      :request-api="getTableList"
      :data-callback="dataCallback"
      v-if="dataLoaded"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" text :icon="CirclePlus" @click="openDrawer('新增')">新增用户</el-button>
        <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
        <el-button type="danger" text :icon="Refresh" @click="_batchResetPsd(scope.selectedListIds)">恢复默认密码</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(1, scope.row)"
          >操作权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(2, scope.row)"
          >部门权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(3, scope.row)"
          >地图权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(4, scope.row)"
          >门禁组权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(5, scope.row)"
          >门禁点权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="_showDialog(6, scope.row)"
          >锁地图权限</el-button
        >
        <el-button type="primary" link :icon="EditPen" :disabled="scope.row!.isDefault" @click="openDrawer('编辑', scope.row)"
          >编辑</el-button
        >
        <!-- <el-button type="primary" link :icon="Refresh" @click="_resetPsd(scope.row)">恢复默认密码</el-button>
        <el-button type="primary" link :icon="Delete" :disabled="scope.row.isDefault" @click="_delete(scope.row)">删除</el-button> -->
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
    <DeptRightsDialog
      :optId="curRow.optid"
      :dialogVisible="dialogVisible"
      :title="'请选择 ' + curRow.optname"
      :curRow="curRow"
      :handleClose="handleClose"
    />
    <TreeDialog
      :rights="rights"
      :zNodes="zNodes"
      :optId="curRow.optid"
      :dialogVisible="dialogVisible1"
      :title="'请选择 ' + curRow.optname"
      :handleType="handleTypeVal"
      :handleClose="handleClose"
    />
    <DoorRightsDialog
      :optId="curRow.optid"
      :dialogVisible="dialogVisible2"
      :title="'请选择 ' + curRow.optname"
      :handleClose="handleClose"
    />
  </div>
</template>

<script setup lang="tsx" name="userInfo">
/* eslint-disable */
// @ts-nocheck
import { ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen, Refresh } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import UserDrawer from "./components/UserDrawer.vue";
import DoorRightsDialog from "./components/DoorRightsDialog.vue";
import DeptRightsDialog from "./components/DeptRightsDialog.vue";
import TreeDialog from "./components/TreeDialog.vue";
import { getOrgTree, getRoomMapTree, getMapTree, getGroupTree } from "@/api/modules/common";

import {
  getUserList,
  delUser,
  editUser,
  addUser,
  resetPsd,
  getDptRights,
  getMapRights,
  getRuleGroupRights,
  getRoomMapRights
} from "@/api/modules/user";
const proTable = ref();
const handleTypeVal = ref(1);
const loading = ref(false);
const dataLoaded = ref(false);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);
const roleList = ref([]);
const deptList = ref([]);
const mapList = ref([]);
const ruleGroupList = ref([]);
const roomMapList = ref([]);
const rights = ref([]);
const zNodes = ref([]);
const curRow = ref({});

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records,
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getUserList(newParams);
};

const columns = [
  { type: "selection", fixed: "left", width: 60 },
  {
    prop: "optcode",
    label: "登录ID",
    minWidth: 200
  },
  {
    prop: "optname",
    label: "名称",
    minWidth: 200
  },
  {
    prop: "bstop",
    label: "停用",
    width: 120,
    render: scope => {
      return (
        <>
          <el-checkbox disabled v-model={scope.row.bstop}></el-checkbox>
        </>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 700 }
];

/**
 * 显示操作弹窗
 */
const _showDialog = async (handleType, row) => {
  curRow.value = row;
  handleTypeVal.value = handleType;

  const zNodesMap = new Map([
    [2, deptList],
    [3, mapList],
    [4, ruleGroupList],
    [6, roomMapList]
  ]);

  const rightsMap = new Map([
    [2, getDptRights],
    [3, getMapRights],
    [4, getRuleGroupRights],
    [6, getRoomMapRights]
  ]);

  if (handleType == 1) {
    dialogVisible.value = true;
  } else if (handleType == 5) {
    dialogVisible2.value = true;
  } else {
    dialogVisible1.value = true;
    zNodes.value = zNodesMap.get(handleType)["value"];
    try {
      const res = await rightsMap.get(handleType)({ optid: row.optid });
      rights.value = res.data;
    } catch (error) {
      console.log(error);
    }
  }
};

// 批量删除用户信息
const _batchDel = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择用户");
    return false;
  }
  const tip = "删除所选用户信息";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        try {
          const res = await delUser({ list: selectedListIds });
          const { v1, v2 } = res.data;
          ElMessage.success(`删除成功：${v1},失败：${v2}`);

          proTable.value.clearSelection();
          proTable.value.reset();
          done();
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      } else {
        done();
      }
    }
  });
};

// 批量恢复默认密码
const _batchResetPsd = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择用户");
    return false;
  }
  const tip = "恢复所选用户密码";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;

        try {
          const res = await resetPsd({ list: selectedListIds });
          const { v1, v2 } = res.data;
          ElMessage.success(`密码重置成功：${v1},失败：${v2}`);
          proTable.value.clearSelection();
          proTable.value.getTableList();
          done();
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      } else {
        done();
      }
    }
  });
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
  dialogVisible2.value = false;
  proTable.value.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addUser : title === "编辑" ? editUser : undefined,
    getTableList: proTable.value.getTableList,
    resetTableList: proTable.value.reset,
    proTable: proTable.value
  };

  drawerRef.value?.acceptParams(params);
};

/**
 * 批量操作回调
 */
const batchCallBack = (tip, count, isFail, selectedListIds) => {
  if (count === selectedListIds.length) {
    if (!isFail) {
      ElMessage({
        type: "success",
        message: `${tip}成功!`
      });
    }
    loading.value = true;
    proTable.value.clearSelection();
    proTable.value.reset();
  }
};

/**
 * 请求部门节点树数据
 */
const getDptList = async () => {
  try {
    const res = await getOrgTree();
    deptList.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 请求地图节点树数据
 */
const getMapList = async () => {
  try {
    const res = await getMapTree();
    mapList.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 请求门禁组结构树数据
 */
const getGroupList = async () => {
  try {
    const res = await getGroupTree();
    ruleGroupList.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 请求锁地图结构树数据
 */
const getRoomMapList = async () => {
  try {
    const res = await getRoomMapTree();
    roomMapList.value = res.data;
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  loading.value = true;
  Promise.all([getDptList(), getMapList(), getGroupList(), getRoomMapList()]).finally(() => {
    dataLoaded.value = true;
  });
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
